//
//  TNMapViewController.m
//  TravelNotes
//
//  Created by 黄锋 on 15/8/24.
//  Copyright (c) 2015年 王浩宇. All rights reserved.
//

#import "TNMapViewController.h"
#import <MapKit/MapKit.h>
#import <AFNetworking.h>
#import "TNDestinationModel.h"
#import "Macro.h"
#import "TNAnnotation.h"
#import <CoreLocation/CoreLocation.h>

#define kURL @"http://chanyouji.com/api/destinations/attractions/*.json?all=true"
#define kDestinationsInfos @"destinationsInfos"

@interface TNMapViewController () <MKMapViewDelegate, CLLocationManagerDelegate>

@property(nonatomic, strong) MKMapView *mapView;
@property(nonatomic, strong) NSMutableArray *annotationArray;
@property(nonatomic, strong) CLLocationManager *location;

@end

@implementation TNMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBarHidden = YES;
    [self creatView];
    [self getData];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}

- (void)creatView
{
    _mapView = [[MKMapView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _mapView.mapType=MKMapTypeStandard;
    _mapView.delegate = self;
    UILongPressGestureRecognizer *longGes = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longGes:)];
    [_mapView addGestureRecognizer:longGes];
    [self.view addSubview:_mapView];
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(10, 10, 30, 30);
    leftButton.backgroundColor = [UIColor blackColor];
    leftButton.layer.masksToBounds = YES;
    leftButton.layer.cornerRadius = 15;
    [leftButton setImage:[UIImage imageNamed:@"BackBarButton"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(popAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftButton];
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(SCREEN_WIDTH - 35, SCREEN_HEIGHT - 45, 30, 30);
    rightButton.backgroundColor = [UIColor blackColor];
    rightButton.layer.masksToBounds = YES;
    rightButton.layer.cornerRadius = 15;
    [rightButton setImage:[UIImage imageNamed:@"dingwei"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(positionAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rightButton];
}

- (void)longGes:(UILongPressGestureRecognizer *)sender
{
    if (sender.state == UIGestureRecognizerStateEnded) {
        _mapView.mapType++;
        _mapView.mapType %= 3;
    }
}


- (void)positionAction
{
    //设置地图可以跟踪位置
    _mapView.userTrackingMode = MKUserTrackingModeFollow;
    _location = [[CLLocationManager alloc] init];
    if (![CLLocationManager locationServicesEnabled]) {
        return;
    }
    //用户没有处理过弹窗,请求处理
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        //请求在应用程序使用的时候使用定位
        [_location requestWhenInUseAuthorization];
    }
    //设置定位精准度
    _location.desiredAccuracy = kCLLocationAccuracyBest;
    //设置定位的频率(每隔多少米定位一次)
    _location.distanceFilter = 1.0;
    _location.delegate = self;
    //开始定位
    [_location startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    [_location stopUpdatingLocation];
}

- (void)popAction
{
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)getData
{
    _annotationArray = [NSMutableArray array];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:[kURL stringByReplacingOccurrencesOfString:@"*" withString:[[[NSUserDefaults standardUserDefaults] objectForKey:kDestinationsInfos] stringValue]] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *array = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        BOOL aaa = YES;
        for (NSDictionary *dic in array) {
            TNDestinationModel *model = [[TNDestinationModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            if (aaa) {
                CLLocationCoordinate2D location = CLLocationCoordinate2DMake([model.lat floatValue], [model.lng floatValue]);
                _mapView.region = MKCoordinateRegionMake(location, MKCoordinateSpanMake(1, 1));
                aaa = NO;
            }
            CLLocationCoordinate2D location = CLLocationCoordinate2DMake([model.lat floatValue], [model.lng floatValue]);
            TNAnnotation *annotation = [[TNAnnotation alloc] init];
            annotation.coordinate = location;
            annotation.title = model.name;
            if (model.user_score) {
                annotation.subtitle = [NSString stringWithFormat:@"评分:%@", model.user_score];
            }
            if (model.attraction_type) {
                annotation.image = [UIImage imageNamed:[NSString stringWithFormat:@"Pin%@Normal", [model.attraction_type capitalizedString]]];
                annotation.leftCalloutAccessoryImage = [UIImage imageNamed:[NSString stringWithFormat:@"A_%@", model.attraction_type]];
            } else {
                annotation.image = [UIImage imageNamed:@"MapPin"];
            }
            [_annotationArray addObject:annotation];
        }
        [_mapView addAnnotations:_annotationArray];
    } failure:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

#pragma mark - MKMapViewDelegate

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[TNAnnotation class]]) {
        static NSString *key1=@"Annotation";
        MKAnnotationView *annotationView=[mapView dequeueReusableAnnotationViewWithIdentifier:key1];
        if (!annotationView) {
            annotationView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key1];
            annotationView.canShowCallout=true;//允许交互点击
            annotationView.calloutOffset=CGPointMake(0, 1);//定义详情视图偏移量
        }
        //修改大头针视图
        //重新设置此类大头针视图的大头针模型(因为有可能是从缓存池中取出来的，位置是放到缓存池时的位置)
        annotationView.annotation=annotation;
        annotationView.image=((TNAnnotation *)annotation).image;//设置大头针视图的图片
        annotationView.leftCalloutAccessoryView=[[UIImageView alloc]initWithImage:((TNAnnotation *)annotation).leftCalloutAccessoryImage];//定义详情左侧视图
        return annotationView;
    } else {
        return nil;
    }
}

@end
